<template>
    <div class="auth-container">
        <el-card class="auth-card">
            <template #header>
                <h2>{{ isUserExist === null ? '用户验证' : (isUserExist ? '用户登录' : '用户注册') }}</h2>
            </template>

            <el-form :model="formData" label-position="top">
                <el-form-item label="用户名">
                    <el-input v-model="formData.username" placeholder="请输入用户名" clearable @blur="handleCheckUser"
                        @keyup.enter="handleCheckUser" />
                </el-form-item>

                <!-- 登录表单 -->
                <template v-if="isUserExist">
                    <el-form-item label="密码">
                        <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password
                            clearable />
                    </el-form-item>

                    <el-form-item label="登录有效期">
                        <el-select v-model="formData.tokenMaxAge" placeholder="请选择登录有效期" style="width: 100%">
                            <el-option label="7天" :value="7" />
                            <el-option label="14天" :value="14" />
                            <el-option label="30天" :value="30" />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleLogin" style="width: 100%">
                            登录
                        </el-button>
                    </el-form-item>
                </template>

                <!-- 注册表单 -->
                <template v-if="isUserExist === false">
                    <el-form-item label="密码">
                        <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password
                            clearable />
                    </el-form-item>

                    <el-form-item label="确认密码">
                        <el-input v-model="formData.confirmPassword" type="password" placeholder="请确认密码" show-password
                            clearable />
                    </el-form-item>

                    <el-form-item label="昵称">
                        <el-input v-model="formData.nickname" placeholder="请输入昵称" clearable />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleRegister" style="width: 100%">
                            注册
                        </el-button>
                    </el-form-item>
                </template>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { checkUserExists, login, register } from '@/api/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const isUserExist = ref(null)
const formData = ref({
    username: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    tokenMaxAge: 7
})

// 检查用户是否存在
const handleCheckUser = async () => {
    if (!formData.value.username) return

    try {
        const data = await checkUserExists(formData.value.username)
        console.log('检查用户 响应体', data)
        isUserExist.value = data.exist
    } catch (error) {
        console.error('检查用户失败:', error)
    }
}

// 处理登录
const handleLogin = async () => {
    try {
        if (!formData.value.username || !formData.value.password) {
            ElMessage.warning('请填写完整的登录信息')
            return
        }

        const res = await login(
            formData.value.username,
            formData.value.password,
            formData.value.tokenMaxAge
        )

        userStore.setUserInfo(res)
        setToken(res.token)
        router.push('/')
    } catch (error) {
        console.error('登录失败:', error)
    }
}

// 处理注册
const handleRegister = async () => {
    try {
        if (!formData.value.username || !formData.value.password ||
            !formData.value.confirmPassword || !formData.value.nickname) {
            ElMessage.warning('请填写完整的注册信息')
            return
        }

        if (formData.value.password !== formData.value.confirmPassword) {
            ElMessage.error('两次输入的密码不一致')
            return
        }

        const res = await register(
            formData.value.username,
            formData.value.password,
            formData.value.confirmPassword,
            formData.value.nickname
        )
        
        userStore.setUserInfo(res)
        setToken(res.token)
        router.push('/')
    } catch (error) {
        console.error('注册失败:', error)
    }
}
</script>

<style scoped>
.auth-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    width: 100%;
    background-color: #f5f7fa;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

.auth-card {
    width: 400px;
    margin: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.auth-card :deep(.el-card__header) {
    text-align: center;
    padding: 20px;
}

.auth-card h2 {
    margin: 0;
    color: #303133;
}
</style>